import pymysql
class MysqlUtil:
    def __init__(self,host,port,user,password,db,charset):
        #连接数据库
        self.conn = pymysql.connect(host=host,port=port,user=user,password=password,database=db,charset=charset)
        #设置自动提交
        self.conn.autocommit(True)
        #获取游标对象
        self.cursor=self.conn.cursor()

    def query(self,sql):
        self.cursor.execute(sql)
        return self.cursor.fetchall()

    def update(self,sql,params=None):
        try:
            self.cursor.execute(sql,params)
            self.conn.commit()

        except Exception as result:
            print(result)
            #回滚
            self.conn.rollback()

    def close(self):
        self.cursor.close()
        self.conn.close()

if __name__ == '__main__':
    host=''
    cn = MysqlUtil(host)
    sql = ''
    print(cn.query(sql))
    cn.close()
